package com.mizhiquan.service.impl;

import com.mizhiquan.common.Const;
import com.mizhiquan.common.ServerResponse;
import com.mizhiquan.dao.*;
import com.mizhiquan.pojo.EmailCode;
import com.mizhiquan.pojo.PhoneCode;
import com.mizhiquan.pojo.User;
import com.mizhiquan.pojo.UserExpand;
import com.mizhiquan.service.IUserService;
import com.mizhiquan.util.CheckUtil;
import com.mizhiquan.util.MD5Util;
import com.mizhiquan.util.RandomCodeUtil;
import com.mizhiquan.util.SendCodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * IUserService实现类
 */
@Service("iUserService")//Spring注解->这是一个Service 参数设置Service的name
public class UserServiceImpl implements IUserService {

    /*
    * 依赖注入
    * 将UserMapper接口注入
    * Spring会自动寻找UserMapper接口实现类
    * 这里会根据UserMapper与UserMapper.xml生成一个代理实现类
    * 方便后面的方法调用
    */
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserExpandMapper userExpandMapper;

    @Autowired
    private PreRegisterMapper preRegisterMapper;

    @Autowired
    private PhoneCodeMapper phoneCodeMapper;

    @Autowired
    private EmailCodeMapper emailCodeMapper;


    @Override
    public ServerResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkNickname(username);
        if(resultCount==0){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        //密码登陆MD5
        String MD5Password = MD5Util.MD5EncodeUtf8(password).toUpperCase();
        User user = userMapper.selectLogin(username,MD5Password);
        if (user!=null){
            user.setPassword(StringUtils.EMPTY);//密码置空保护用户隐私
            return ServerResponse.createBySuccess("登陆成功",user);
        }
        return ServerResponse.createByErrorMessage("密码错误");
    }

    @Override
    public ServerResponse<String> register(User user) {
        int flag = -1;
        ServerResponse validRespinse = this.checkValid(user.getNickname(),Const.USERNAME);
        if(!validRespinse.isSuccess()){
            return validRespinse;
        }
        //客户端只发送了email参数，没有发送phone参数
        if(StringUtils.isNotBlank(user.getEmail())&&StringUtils.isBlank(user.getPhone())){
            validRespinse = this.checkValid(user.getEmail(),Const.EMAIL);
            if(!validRespinse.isSuccess()){
                return validRespinse;
            }
            flag = 0;
        }else{ //其他情况，如两个都发，两个都不发，只发了phone，只走手机激活，邮箱置空
            validRespinse = this.checkValid(user.getPhone(),Const.PHONE);
            if(!validRespinse.isSuccess()){
                return validRespinse;
            }
            user.setEmail(null);
            flag = 1;
        }
        //检测密码和手机号格式正确性
        if(!CheckUtil.checkPass(user.getPassword())||!CheckUtil.checkPhone(user.getPhone()))
            return ServerResponse.createByErrorMessage("手机号或密码格式不正确");
        //设置userid
        String uuid = UUID.randomUUID().toString().toUpperCase(); //获取UUID并转化为String对象
        uuid = uuid.replace("-", "");//因为UUID本身为32位只是生成时多了“-”，所以将它们去点就可
        user.setUserid(uuid);
        user.setRole(Const.Role.ROLE_PRE_REG);
        user.setuFrom(Const.From.FromWeb);
        user.setOuterId(RandomCodeUtil.getRandomNum(8,false));
        user.setRegTime(new Date());
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()).toUpperCase());
        //插入到预注册表
        int resultCount1 = preRegisterMapper.insert(user);
        if(resultCount1 == 0){
            return ServerResponse.createByErrorMessage("预注册失败");
        }
        Boolean sendok = false;

        if(flag==0){ //发送邮件激活
            sendok = SendCodeUtil.sendEmail(user.getEmail(),Const.EMAILTimeOut,user.getUserid(),user.getOuterId());
        }else if(flag==1) //发送短信激活
            sendok = SendCodeUtil.sendSMSCode(user.getPhone(),Const.SMSTimeOut,user.getUserid(),Const.SMSTemplet.REGISTER);
        if(sendok){
            return ServerResponse.createBySuccessMessage("预注册成功");
        }else{
            return ServerResponse.createByErrorMessage("预注册失败");
        }

    }


    //邮箱、昵称和手机号校验
    @Override
    public ServerResponse<String> checkValid(String str, String type){
        if(StringUtils.isNoneBlank(str,type)){
            //开始校验
            if(Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount == 0 ){
                    return ServerResponse.createBySuccessMessage("用户名校验成功");
                }else{
                    return ServerResponse.createByErrorMessage("用户已存在");
                }
            }else if(Const.EMAIL.equals(type)){
                if(!CheckUtil.checkEmail(str))
                    return  ServerResponse.createByErrorMessage("邮箱格式错误");
                int resultCount = userMapper.checkEmail(str);
                if (resultCount == 0 ){
                    return ServerResponse.createBySuccessMessage("邮箱校验成功");
                }else{
                    return ServerResponse.createByErrorMessage("邮箱已存在");
                }
            }else if(Const.PHONE.equals(type)){
                if(!CheckUtil.checkPhone(str))
                    return  ServerResponse.createByErrorMessage("手机号格式错误");
                int resultCount = userMapper.checkPhone(str);
                if (resultCount == 0 ){
                    return ServerResponse.createBySuccessMessage("手机号校验成功");
                }else{
                    return ServerResponse.createByErrorMessage("手机号已存在");
                }
            }else{
                return  ServerResponse.createByErrorMessage("参数错误");
            }
        }else {
            return  ServerResponse.createByErrorMessage("参数错误");
        }

    }


    //修改密码
    @Override
    public ServerResponse<String> changePass(String oldpass, String newpass){
        if(StringUtils.isNoneBlank(oldpass,newpass)){

            return ServerResponse.createBySuccessMessage("密码修改成功");
        }else{
            return  ServerResponse.createByErrorMessage("参数错误");
        }

    }

    //忘记密码
    @Override
    public ServerResponse<String> forgetPass(String type,String value){
        if(StringUtils.isNoneBlank(type,value)){
            if(Const.PHONE.equals(type)){

                return ServerResponse.createBySuccessMessage("密码修改成功");

            }else if(Const.EMAIL.equals(type)){

                return ServerResponse.createBySuccessMessage("密码修改成功");

            }else{
                return  ServerResponse.createByErrorMessage("参数错误");
            }
        }else{
            return  ServerResponse.createByErrorMessage("参数错误");
        }

    }

    //手机、邮箱的验证激活
    @Override
    public ServerResponse<String> Activate(String type, String value, String code, String outerId){
        if(StringUtils.isNoneBlank(type,value,code)){
            if(Const.PHONE.equals(type)){
                if(!CheckUtil.checkPhone(value))
                    return  ServerResponse.createByErrorMessage("手机号格式错误");
                PhoneCode phoneCode = phoneCodeMapper.selectByPrimaryKey(code);
                if(phoneCode==null||!value.equals(phoneCode.getPhone()))
                    return  ServerResponse.createByErrorMessage("验证码错误");
                if(phoneCode.getUsed()|| CheckUtil.isTimeOut(phoneCode.getTime(),phoneCode.getTimeout()))
                    return  ServerResponse.createByErrorMessage("验证码已失效，请重新发起");
                phoneCode.setUsed(true);
                int result = phoneCodeMapper.updateByPrimaryKey(phoneCode);
                if(result > 0 ){
                    return initUser(phoneCode.getUserId());
                }else
                    return  ServerResponse.createByErrorMessage("账号激活失败");
            }else if(Const.EMAIL.equals(type)){
                if(!CheckUtil.checkEmail(value))
                    return  ServerResponse.createByErrorMessage("邮箱格式错误");
                EmailCode emailCode = emailCodeMapper.selectByPrimaryKey(code);
                if(emailCode==null||!value.equals(emailCode.getEmail())||!outerId.equals(emailCode.getOuterId()))
                    return  ServerResponse.createByErrorMessage("验证码错误");
                if(emailCode.getUsed()|| CheckUtil.isTimeOut(emailCode.getTime(),emailCode.getTimeout()))
                    return  ServerResponse.createByErrorMessage("验证码已失效，请重新发起");
                emailCode.setUsed(true);
                int result = emailCodeMapper.updateByPrimaryKey(emailCode);
                if(result > 0 ){
                    return initUser(emailCode.getUserId());
                }else
                    return  ServerResponse.createByErrorMessage("账号激活失败");

            }else{
                return  ServerResponse.createByErrorMessage("参数错误");
            }
        }else{
            return  ServerResponse.createByErrorMessage("参数错误");
        }
    }

    //激活成功，初始化用户
    private  ServerResponse initUser(String userId){
        //先从预注册表得到user实例
        User user = preRegisterMapper.selectByPrimaryKey(userId);
        //修改角色为普通用户
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //从预注册表删除
        int resultCount = preRegisterMapper.deleteByPrimaryKey(userId);
        if(resultCount == 0){
            return  ServerResponse.createByErrorMessage("账号激活失败");
        }
        //插入到用户表
        int resultCount1 = userMapper.insert(user);
        if(resultCount1 == 0){
            return ServerResponse.createByErrorMessage("账号激活失败");
        }
        //插入到User扩展表
        UserExpand userExpand = new UserExpand(user.getUserid(),0,0,0,0,0,0,0);
        int resultCount2 = userExpandMapper.insert(userExpand);
        if(resultCount2 == 0 ){
            return ServerResponse.createByErrorMessage("账号激活失败");
        }
        return ServerResponse.createBySuccessMessage("账号激活成功");
    }
}
